package com.saikuo.service.service.impl;

import com.saikuo.service.elasticsearch.ElasticsearchHandler;
import com.saikuo.service.service.ISearchService;
import com.saikuo.service.vo.MedicineView;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by work on 2016/10/25.
 */
@Service
public class SearchServiceImpl implements ISearchService {
    private static final Logger logger = LoggerFactory.getLogger("search");

    @Override
    public List<MedicineView> searchMedicine(String searchTxt, int from) {
        if (StringUtils.isEmpty(searchTxt)) {
            return Collections.emptyList();
        }
        QueryBuilder queryBuilder = QueryBuilders
                .boolQuery()
                .should(QueryBuilders.matchQuery("name", searchTxt))
                .should(QueryBuilders.matchQuery("introduction", searchTxt))
                .should(QueryBuilders.matchQuery("direction", searchTxt));
        ElasticsearchHandler elasticsearchHandler = new ElasticsearchHandler();
        try {
            SearchHit[] searchHits = elasticsearchHandler.searcher(queryBuilder, "medicine", from);
            logger.info("search result======" + searchHits);
            if (searchHits.length > 0) {
                List<MedicineView> result = new ArrayList<>(searchHits.length);
                for (SearchHit hit : searchHits) {
                    MedicineView medicineView = new MedicineView();
                    medicineView.setId((Integer) hit.getSource().get("id"));
                    medicineView.setName((String) hit.getSource().get("name"));
                    medicineView.setMedicineNum((String) hit.getSource().get("num"));
                    medicineView.setIntroduction((String) hit.getSource().get("introduction"));
                    medicineView.setPrice(hit.getSource().get("price").toString());
                    medicineView.setSpecification((String) hit.getSource().get("specification"));
                    medicineView.setHeadPic((String) hit.getSource().get("head_pic"));
                    result.add(medicineView);
                }
                return result;
            }
            return Collections.emptyList();
        } catch (UnknownHostException e) {
            logger.error("search error======", e);
        }
        return Collections.emptyList();
    }
}
